﻿using System;
using System.Collections;
using System.Collections.Generic;
using DigitsNFCToolkit;
using GameFramework;
using UnityEngine;
using UnityGameFramework.Runtime;

namespace StarForce
{
    /// <summary>
    /// NFC 功能详情
    /// </summary>
    public class NFCComponents : GameFrameworkComponent
    {
	    /// <summary>
	    /// 判断设备是否支持NFC
	    /// </summary>
	    [HideInInspector]
        public bool ISSupportNFC;

	    /// <summary>
	    /// 设备 是否支持NDEF读取
	    /// </summary>
	    [HideInInspector]
	    public bool IsNDEFReadSupported;

	    /// <summary>
	    /// 设备 是否支持NDEF写入
	    /// </summary>
	    [HideInInspector]
	    public bool IsNDEFWriteSupported;

	    /// <summary>
	    /// 设备 NFC是否开启
	    /// </summary>
	    [HideInInspector]
	    public bool IsNFCEnabled;

	    /// <summary>
	    /// 设备 是否支持NDEF读取
	    /// </summary>
	    [HideInInspector]
	    public bool IsNDEFPushEnabled;

	    [HideInInspector]
	    public bool IsEditorOrAndroid;

	    private Action<NDEFWriteResult> m_ONNDEFWriteFinished; 
	    
	    private Action<NDEFPushResult> m_ONNDEFPushFinished;

	    private Action<NDEFReadResult> m_ONNDEFReadResult;

	    private NDEFMessage m_pendingMessage;
	    
	    private const string TAG_INFO_FORMAT = "ID: {0}\nTechnologies: {1}\nManufacturer: {2}\nWritable: {3}\nMaxWriteSize: {4}";

	    /// <summary>
	    /// 写入信息事件注册
	    /// </summary>
	    public event Action<NDEFWriteResult> OnndefWriteFinished
	    {
		    add
		    {
			    m_ONNDEFWriteFinished -= value;
			    m_ONNDEFWriteFinished += value;
		    }
		    remove
		    {
			    m_ONNDEFWriteFinished -= value;
		    }
	    }
	    
	    /// <summary>
	    /// 阅读NFC信息回调
	    /// </summary>
	    public event Action<NDEFReadResult> OnndefReadResult
	    {
		    add
		    {
			    m_ONNDEFReadResult -= value;
			    m_ONNDEFReadResult += value;
		    }
		    remove
		    {
			    m_ONNDEFReadResult -= value;
		    }
	    }

	    /// <summary>
	    /// 写入信息推送事件注册
	    /// </summary>
	    public event Action<NDEFPushResult> OnndefPushFinished
	    {
		    add
		    {
			    m_ONNDEFPushFinished -= value;
			    m_ONNDEFPushFinished += value;
		    }
		    remove
		    {
			    m_ONNDEFPushFinished -= value;
		    }
	    }

	    void Start()
	    {
		    IsEditorOrAndroid = false;
	        Log.Info("开启NFC");
#if (!UNITY_EDITOR) && UNITY_ANDROID
	        IsEditorOrAndroid = true;
#endif
#if (!UNITY_EDITOR)
			NativeNFCManager.AddNFCTagDetectedListener(OnNFCTagDetected);
			NativeNFCManager.AddNDEFReadFinishedListener(OnNDEFReadFinished);
IsEditorOrAndroid = true;
ISSupportNFC = NativeNFCManager.IsNFCTagInfoReadSupported();
IsNDEFReadSupported = NativeNFCManager.IsNDEFReadSupported();
IsNDEFWriteSupported = NativeNFCManager.IsNDEFWriteSupported();
IsNFCEnabled = NativeNFCManager.IsNFCEnabled();
IsNDEFPushEnabled = NativeNFCManager.IsNDEFPushEnabled();
			Debug.Log("NFC Tag Info Read Supported: " + NativeNFCManager.IsNFCTagInfoReadSupported());
			Debug.Log("NDEF Read Supported: " + NativeNFCManager.IsNDEFReadSupported());
			Debug.Log("NDEF Write Supported: " + NativeNFCManager.IsNDEFWriteSupported());
			Debug.Log("NFC Enabled: " + NativeNFCManager.IsNFCEnabled());
			Debug.Log("NDEF Push Enabled: " + NativeNFCManager.IsNDEFPushEnabled());
	        
	        
	        NativeNFCManager.AddNDEFWriteFinishedListener(OnNDEFWriteFinished);
			NativeNFCManager.AddNDEFPushFinishedListener(OnNDEFPushFinished);
#endif
	        // m_ISSupportNFC = NativeNFCManager.IsNFCTagInfoReadSupported();
	        // m_IsNDEFReadSupported = NativeNFCManager.IsNDEFReadSupported();
	        // m_IsNDEFWriteSupported = NativeNFCManager.IsNDEFWriteSupported();
	        // m_IsNFCEnabled = NativeNFCManager.IsNFCEnabled();
	        // m_IsNDEFPushEnabled = NativeNFCManager.IsNDEFPushEnabled();
        }

	    private void Update()
	    {
// #if (!UNITY_EDITOR) && UNITY_ANDROID
// ISSupportNFC = NativeNFCManager.IsNFCTagInfoReadSupported();
// IsNDEFReadSupported = NativeNFCManager.IsNDEFReadSupported();
// IsNDEFWriteSupported = NativeNFCManager.IsNDEFWriteSupported();
// IsNFCEnabled = NativeNFCManager.IsNFCEnabled();
// IsNDEFPushEnabled = NativeNFCManager.IsNDEFPushEnabled();
// #endif
	    }

	    void OnEnable()
	    {
		    Log.Info("开启NFC11111");
#if (!UNITY_EDITOR) && !UNITY_IOS
NativeNFCManager.Enable();
#endif
	    }

	    void OnDisable()
	    {
		    Log.Info("开启NFC444");
#if (!UNITY_EDITOR) && !UNITY_IOS
 NativeNFCManager.Disable();
#endif
	    }

	    public void ClearNDEF()
	    {
		    m_pendingMessage = null;
	    }

	    /* --------------------------------------todo 读取操作区域 --------------------------------------------------*/
	    
        /// <summary>
        /// 读取NFC 标签信息
        /// </summary>
        public void ReadNFC()
        {
#if (!UNITY_EDITOR)
			NativeNFCManager.ResetOnTimeout = true;
			NativeNFCManager.Enable();
#endif
        }

        private void OnNFCTagDetected(NFCTag tag)
        {
	        string technologiesString = string.Empty;
	        NFCTechnology[] technologies = tag.Technologies;
	        int length = technologies.Length;
	        for(int i = 0; i < length; i++)
	        {
		        if(i > 0)
		        {
			        technologiesString += ", ";
		        }

		        technologiesString += technologies[i].ToString();
	        }

	        string maxWriteSizeString = string.Empty;
	        if(tag.MaxWriteSize > 0)
	        {
		        maxWriteSizeString = tag.MaxWriteSize + " bytes";
	        }
	        else
	        {
		        maxWriteSizeString = "Unknown";
	        }

	        string tagInfo = string.Format(TAG_INFO_FORMAT, tag.ID, technologiesString, tag.Manufacturer, tag.Writable, maxWriteSizeString);
	        Log.Info("tagInfo:{0}",tagInfo);
        }

        private void OnNDEFReadFinished(NDEFReadResult result)
        {
	        string readResultString = string.Empty;
	        m_ONNDEFReadResult.Invoke(result);
	        if(result.Success)
	        {
		        readResultString = string.Format("NDEF Message was 阅读 successfully from tag {0}", result.TagID);
	        }
	        else
	        {
		        readResultString = string.Format("阅读失败 to read NDEF Message from tag {0}\nError: {1}", result.TagID, result.Error);
	        }
	        Log.Info("阅读NDEF标签：{0}",readResultString);
        }
        
        
        
        /* --------------------------------------todo 写入操作区域 --------------------------------------------------*/

        /// <summary>
        /// 写入NFC 标签信息
        /// </summary>
        /// <param name="content">传输内容</param>
        /// <param name="languageCode">传输国际格式 -- 默认en</param>
        /// <param name="ndefRecordType">传输内容类型 默认TEXT</param>
        public void WriteNFC(string content, string languageCode = "en", NDEFRecordType ndefRecordType = NDEFRecordType.TEXT)
        {
	        if (m_pendingMessage == null)
	        {
		        m_pendingMessage = new NDEFMessage();
	        }

	        NDEFRecord record = null;
	        
	        switch (ndefRecordType)
	        {
		        case NDEFRecordType.TEXT:
			        record = new TextRecord(content, languageCode, TextRecord.TextEncoding.UTF8);
			        break;
		        case NDEFRecordType.URI:
			        break;
		        case NDEFRecordType.MIME_MEDIA:
			        break;
		        case NDEFRecordType.EXTERNAL_TYPE:
			        break;
	        }
	        
	        m_pendingMessage.Records.Add(record);

	        List<NDEFRecord> records = m_pendingMessage.Records;
	        for (int i = 0; i < records.Count; i++)
	        {
		        NDEFRecord rec = records[i];
		        TextRecord textRecord = (TextRecord)rec;
		        Log.Info("写入信息内容{0} : {1} , {2} , {3}", i, textRecord.text, textRecord.languageCode, textRecord.textEncoding);
	        }

	        // todo 写入信息
	        if (m_pendingMessage != null)
	        {
#if (!UNITY_EDITOR)
				NativeNFCManager.RequestNDEFWrite(m_pendingMessage);
#if UNITY_ANDROID
				
#elif UNITY_IOS
                NativeNFCManager.Enable(); //Show native popup
#endif
#endif
		        
#if(!UNITY_EDITOR) && UNITY_ANDROID
NativeNFCManager.RequestNDEFPush(m_pendingMessage);
#endif
		        // todo 写入并信息推送出去了 --- 等待其他设备的响应
		        
	        }
        }

        /// <summary>
        /// NDEFWrite 写入完成回调
        /// </summary>
        /// <param name="result"></param>
        private void OnNDEFWriteFinished(NDEFWriteResult result)
        {
	        DealTheWriteMessage(result.Message);
	        m_ONNDEFWriteFinished.Invoke(result);
	        string writeResultString = string.Empty;
	        if(result.Success)
	        {
		        writeResultString = Utility.Text.Format("NDEF 信息写入 successfully to tag {0}", result.TagID);
	        }
	        else
	        {
		        writeResultString = Utility.Text.Format("NDEF 信息写入失败 to 写入 to tag {0}\nError: {1}", result.TagID, result.Error);
	        }
	        Log.Info(writeResultString);
        }

        /// <summary>
        /// NDEFPushFinished 推送完成回调
        /// </summary>
        /// <param name="result"></param>
        private void OnNDEFPushFinished(NDEFPushResult result)
        {
	        DealTheWriteMessage(result.Message);
	        m_ONNDEFPushFinished.Invoke(result);
	        string pushResultString = string.Empty;

	        if (result.Success)
	        {
		        pushResultString = "NDEF Message 推送 successfully to other device";
	        }
	        else
	        {
		        pushResultString = "NDEF Message 推送失败 to push to other device";
	        }
	        
	        Log.Info(pushResultString);
        }

        /// <summary>
        ///  处理写入格式信息
        /// </summary>
        private void DealTheWriteMessage(NDEFMessage message)
        {
	        
        }
    }
}